package itsm.isperp.framework.data.backup;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 
 * 数据库工具
 * 
 * @author lizx
 * @date 2014-6-16
 * @since 1.0
 * 
 */
public class DatabaseUtils {

	/**
	 * 获取安装目录
	 * 
	 * @return
	 */
	public static String getBasedir(JdbcTemplate jdbc) {
		String sql = "SHOW VARIABLES  WHERE variable_name='basedir'";

		return jdbc.queryForMap(sql).get("Value").toString();
	}

	/**
	 * 获取当前数据库名称
	 * 
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	public static String getCurrentDatabaseName(Connection connection)
			throws SQLException {
		return connection.getCatalog();

	}

	/**
	 * 备份数据（通过调用Mysql安装目录下的命令实现）
	 * 
	 * @param jdbc
	 * @param f
	 * @throws IOException
	 * @throws SQLException
	 * @throws InterruptedException
	 */
	public static void backup(JdbcTemplate jdbc, File f) throws IOException,
			SQLException, InterruptedException {

		File file = f.getParentFile();

		if (!file.exists()) {
			file.mkdirs();
		}
		if (f.exists()) {
			f.delete();
			f.createNewFile();
		} else {
			f.createNewFile();
		}
		
		ProcessBuilder pb = new ProcessBuilder(getBasedir(jdbc) + "bin"
				+ File.separator + "mysqldump", "--user=root",
				"--password=root", jdbc.getDataSource().getConnection()
						.getCatalog(), "--result-file=" + f.getPath());
		Process p = pb.start();

		p.waitFor();

	}
}
